{% extends "layout.html" %}

{% block title %}智能搜索 - Google{% endblock %}

{% block css %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/search.css') }}">
{% endblock %}

{% block page_title %}智能搜索系统{% endblock %}

{% block content %}
<div class="search-container centered">
    <div class="search-header">
        <h1>Google搜索</h1>
    </div>

    <div class="search-box">
        <input type="text" id="search-input" placeholder="输入搜索关键词...">
        <button id="search-button">
            <svg class="search-icon" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                <path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
            </svg>
        </button>
    </div>
    
    <div class="search-tabs">
        <div class="search-tab active" data-type="all">全部</div>
        <div class="search-tab" data-type="web">网页</div>
        <div class="search-tab" data-type="image">图片</div>
        <div class="search-tab" data-type="video">视频</div>
        <div class="search-tab" data-type="news">新闻</div>
    </div>
</div>

<div class="loading-results" id="loading">
    <img src="{{ url_for('static', filename='images/loading.gif') }}" alt="加载中">

    <p>正在加载结果...</p>
</div>
<div class="error" id="error-message"></div>

<div class="results-container" id="results-container"></div>

<!-- 添加分页控件 -->
<div class="pagination-container" id="pagination-container"></div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const resultsContainer = document.getElementById('results-container');
        const loadingElement = document.getElementById('loading');
        const errorElement = document.getElementById('error-message');
        const searchTabs = document.querySelectorAll('.search-tab');
        const searchTabsContainer = document.querySelector('.search-tabs');
        const searchContainer = document.querySelector('.search-container');
        const paginationContainer = document.getElementById('pagination-container');
        
        let currentSearchType = 'all'; // 默认搜索类型
        let currentQuery = ''; // 当前搜索关键词
        let currentPage = 1; // 当前页码
        
        // 添加搜索类型切换
        searchTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有激活状态
                searchTabs.forEach(t => t.classList.remove('active'));
                // 激活当前选择的按钮
                this.classList.add('active');
                // 更新当前搜索类型
                currentSearchType = this.getAttribute('data-type');
                
                // 如果已经有搜索内容，则触发新的搜索
                if (searchInput.value.trim()) {
                    currentPage = 1; // 切换类型时重置页码
                    performSearch();
                }
            });
        });

        // 添加搜索按钮点击事件
        searchButton.addEventListener('click', function() {
            currentPage = 1; // 新搜索时重置页码
            performSearch();
        });
        
        // 添加回车键搜索功能
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                currentPage = 1; // 新搜索时重置页码
                performSearch();
            }
        });

        function performSearch() {
            const query = searchInput.value.trim();
            if (!query) {
                showError('请输入搜索关键词');
                return;
            }
            
            currentQuery = query; // 保存当前查询

            // 显示加载状态，清空之前的结果和错误
            loadingElement.style.display = 'block';
            resultsContainer.innerHTML = '';
            errorElement.style.display = 'none';
            paginationContainer.innerHTML = ''; // 清空分页
            
            // 将搜索框移至顶部
            searchContainer.classList.remove('centered');
            searchContainer.classList.add('top');

            // 发送请求到后端API
            fetch(`/search/api?query=${encodeURIComponent(query)}&type=${currentSearchType}&page=${currentPage}`)
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.error || '搜索请求失败');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    loadingElement.style.display = 'none';
                    
                    // 显示选项卡和结果容器
                    searchTabsContainer.style.display = 'flex';
                    resultsContainer.style.display = 'block';
                    
                    // 从响应中获取结果和分页信息
                    const results = data.results || [];
                    const pagination = data.pagination || {
                        current_page: 1,
                        total_pages: 1,
                        total_results: 0,
                        results_per_page: 10
                    };
                    
                    if (results.length === 0) {
                        resultsContainer.innerHTML = '<p class="no-results">没有找到相关结果</p>';
                        paginationContainer.style.display = 'none';
                        return;
                    }
                    
                    // 清空结果容器
                    resultsContainer.innerHTML = '';
                    
                    // 显示搜索结果数量
                    const resultsStats = document.createElement('div');
                    resultsStats.className = 'results-stats';
                    resultsStats.textContent = `找到约 ${pagination.total_results} 条结果（第 ${pagination.current_page} 页，共 ${pagination.total_pages} 页）`;
                    resultsContainer.appendChild(resultsStats);
                    
                    // 根据不同的搜索类型，使用不同的布局
                    if (currentSearchType === 'image') {
                        // 图片搜索布局
                        const imageGrid = document.createElement('div');
                        imageGrid.className = 'image-results-grid';
                        resultsContainer.appendChild(imageGrid);
                        
                        results.forEach(item => {
                            const imageItem = document.createElement('div');
                            imageItem.className = 'image-result-item';
                            
                            // 创建缩略图
                            const img = document.createElement('img');
                            img.className = 'image-result-thumbnail';
                            img.src = item.thumbnail || 'https://via.placeholder.com/200x180?text=无图片';
                            img.alt = item.title;
                            img.loading = 'lazy'; // 懒加载
                            
                            // 创建标题
                            const title = document.createElement('div');
                            title.className = 'image-result-title';
                            title.title = item.title; // 标题提示
                            title.textContent = item.title;
                            
                            // 创建链接
                            const link = document.createElement('div');
                            link.className = 'image-result-link';
                            
                            // 使用 displayLink 或从 URL 提取域名
                            let displayUrl = '';
                            try {
                                if (item.displayLink) {
                                    displayUrl = item.displayLink;
                                } else {
                                    const url = new URL(item.link);
                                    displayUrl = url.hostname.replace('www.', '');
                                }
                            } catch (e) {
                                displayUrl = '链接';
                            }
                            
                            link.textContent = displayUrl;
                            
                            // 添加点击事件
                            imageItem.addEventListener('click', () => {
                                window.open(item.link, '_blank');
                            });
                            
                            imageItem.appendChild(img);
                            imageItem.appendChild(title);
                            imageItem.appendChild(link);
                            
                            imageGrid.appendChild(imageItem);
                        });
                    } else if (currentSearchType === 'video') {
                        // 视频搜索布局
                        results.forEach(item => {
                            const videoItem = document.createElement('div');
                            videoItem.className = 'video-result-item';
                            
                            // 视频缩略图容器
                            const thumbnailContainer = document.createElement('div');
                            thumbnailContainer.className = 'video-thumbnail-container';
                            
                            // 视频缩略图
                            const thumbnail = document.createElement('img');
                            thumbnail.className = 'video-thumbnail';
                            thumbnail.src = item.thumbnail || 'https://via.placeholder.com/200x112?text=无视频缩略图';
                            thumbnail.alt = item.title;
                            
                            thumbnailContainer.appendChild(thumbnail);
                            
                            // 添加视频时长标签（如果有）
                            if (item.duration) {
                                const duration = document.createElement('div');
                                duration.className = 'video-duration';
                                duration.textContent = item.duration;
                                thumbnailContainer.appendChild(duration);
                            }
                            
                            // 视频内容区域
                            const content = document.createElement('div');
                            content.className = 'video-content';
                            
                            // 视频标题
                            const title = document.createElement('a');
                            title.className = 'result-title';
                            title.href = item.link;
                            title.target = '_blank';
                            title.textContent = item.title;
                            
                            // 视频来源
                            const link = document.createElement('div');
                            link.className = 'result-link';
                            link.textContent = item.link;
                            
                            // 视频描述
                            const snippet = document.createElement('div');
                            snippet.className = 'result-snippet';
                            snippet.textContent = item.snippet;
                            
                            content.appendChild(title);
                            content.appendChild(link);
                            content.appendChild(snippet);
                            
                            videoItem.appendChild(thumbnailContainer);
                            videoItem.appendChild(content);
                            
                            resultsContainer.appendChild(videoItem);
                        });
                    } else if (currentSearchType === 'news') {
                        // 新闻搜索布局
                        results.forEach(item => {
                            const newsItem = document.createElement('div');
                            newsItem.className = 'news-result-item';
                            
                            // 新闻内容区域
                            const content = document.createElement('div');
                            content.className = 'news-content';
                            
                            // 新闻来源和时间
                            const sourceContainer = document.createElement('div');
                            sourceContainer.className = 'news-source';
                            
                            // 提取域名作为来源（从链接中）
                            let source = '';
                            try {
                                const url = new URL(item.link);
                                source = url.hostname.replace('www.', '');
                            } catch(e) {
                                source = '未知来源';
                            }
                            
                            sourceContainer.textContent = source;
                            
                            // 显示时间（这里是模拟的）
                            const timeElem = document.createElement('span');
                            timeElem.className = 'news-time';
                            timeElem.textContent = item.pubTime || '近期'; // 使用API返回的时间
                            
                            sourceContainer.appendChild(timeElem);
                            
                            // 新闻标题
                            const title = document.createElement('a');
                            title.className = 'result-title';
                            title.href = item.link;
                            title.target = '_blank';
                            title.textContent = item.title;
                            
                            // 新闻摘要
                            const snippet = document.createElement('div');
                            snippet.className = 'result-snippet';
                            snippet.textContent = item.snippet;
                            
                            content.appendChild(sourceContainer);
                            content.appendChild(title);
                            content.appendChild(snippet);
                            
                            // 如果有缩略图，添加缩略图
                            if (item.thumbnail) {
                                const thumbnailContainer = document.createElement('div');
                                thumbnailContainer.className = 'news-thumbnail';
                                
                                const thumbnail = document.createElement('img');
                                thumbnail.src = item.thumbnail;
                                thumbnail.alt = item.title;
                                
                                thumbnailContainer.appendChild(thumbnail);
                                newsItem.appendChild(content);
                                newsItem.appendChild(thumbnailContainer);
                            } else {
                                newsItem.appendChild(content);
                            }
                            
                            resultsContainer.appendChild(newsItem);
                        });
                    } else {
                        // 网页搜索布局（默认）
                        results.forEach(item => {
                            const resultItem = document.createElement('div');
                            resultItem.className = 'result-item';
                            
                            const title = document.createElement('a');
                            title.className = 'result-title';
                            title.href = item.link;
                            title.target = '_blank';
                            title.textContent = item.title;
                            
                            const link = document.createElement('div');
                            link.className = 'result-link';
                            link.textContent = item.link;
                            
                            const snippet = document.createElement('div');
                            snippet.className = 'result-snippet';
                            snippet.textContent = item.snippet;
                            
                            resultItem.appendChild(title);
                            resultItem.appendChild(link);
                            resultItem.appendChild(snippet);
                            
                            resultsContainer.appendChild(resultItem);
                        });
                    }
                    
                    // 创建分页控件
                    createPagination(pagination);
                })
                .catch(error => {
                    loadingElement.style.display = 'none';
                    showError(error.message);
                });
        }
        
        // 创建分页控件
        function createPagination(pagination) {
            if (pagination.total_pages <= 1) {
                paginationContainer.style.display = 'none';
                return;
            }
            
            paginationContainer.style.display = 'flex';
            paginationContainer.innerHTML = '';
            
            const currentPage = pagination.current_page;
            const totalPages = pagination.total_pages;
            
            // 确定显示的页码范围
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, startPage + 4);
            
            // 调整起始页，确保显示5个页码（如果有那么多）
            if (endPage - startPage < 4 && totalPages > 4) {
                startPage = Math.max(1, endPage - 4);
            }
            
            // 添加上一页按钮
            if (currentPage > 1) {
                addPageButton('上一页', currentPage - 1, false);
            }
            
            // 添加第一页按钮和省略号
            if (startPage > 1) {
                addPageButton('1', 1, false);
                if (startPage > 2) {
                    addEllipsis();
                }
            }
            
            // 添加页码按钮
            for (let i = startPage; i <= endPage; i++) {
                addPageButton(i.toString(), i, i === currentPage);
            }
            
            // 添加省略号和最后一页按钮
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    addEllipsis();
                }
                addPageButton(totalPages.toString(), totalPages, false);
            }
            
            // 添加下一页按钮
            if (currentPage < totalPages) {
                addPageButton('下一页', currentPage + 1, false);
            }
        }
        
        // 添加页码按钮
        function addPageButton(text, page, isActive) {
            const button = document.createElement('div');
            button.className = `pagination-button ${isActive ? 'active' : ''}`;
            button.textContent = text;
            
            if (!isActive) {
                button.addEventListener('click', () => {
                    currentPage = page;
                    performSearch();
                    
                    // 滚动到页面顶部
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                });
            }
            
            paginationContainer.appendChild(button);
        }
        
        // 添加省略号
        function addEllipsis() {
            const ellipsis = document.createElement('div');
            ellipsis.className = 'pagination-ellipsis';
            ellipsis.textContent = '...';
            paginationContainer.appendChild(ellipsis);
        }

        function showError(message) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
    });
</script>
{% endblock %} 